<?php

namespace common\observer;

use common\model\TaskModel;
use support\SingletonTrait;
use common\model\VersionModel;
use common\service\StatusService;
use common\service\TenantEventService;
use teamones\dbeventObserver\interfaces\SplObserver;
use teamones\dbeventObserver\interfaces\SplSubject;

/**
 * 任务进入待发布状态  推送自动发布事件到租户通道
 */
class TaskReadyToPublishPushTenantEvent implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['task_status'])) {
            return;
        }
        if ($updateData['task_status'] != StatusService::getInstance()->getTaskReadyToPublishStatus()['id']) {
            return;
        }
        $task = $subject->getSubjectData();
        if (empty($task) ||
            in_array($task['executor_type'], TaskModel::OUTSIDE_EXECUTE_TYPE_GROUP)
        ) {
            return;
        }
        // 租户是否有deadlineHost服务配置
        request()->getTenantId($task['tenant_id']);
        $tenantOption = teamones_request('teamones-im', 'tenant_options/find', ['param' => ['filter' => [
            'tenant_id' => $task['tenant_id'],
        ]]])['data'];
        if (empty($tenantOption['config']['deadlineHost'])) {
            APP_DEBUG && trace('don`t have tenant_options deadlineHost config', 'DEBUG');
            return;
        }

        $version = model(VersionModel::class)->where(['link_id' => $subject->getSplPrimaryId()])->order('id desc')->find();
        if (empty($version) || $version['is_publish'] != 'no') {
            return;
        }
        try {
            TenantEventService::getInstance()->push($task['tenant_id'], 'version_wait_publish', ['version_id' => $version['id'], 'task_id' => $task['id'], 'param' => $version['param']]);
        } catch (\Throwable $e) {
            trace('推送自动发布事件失败' . format_exception_info($e), 'ERR');
        }
    }

}
